<?php

namespace wechat;

/**
 * 微信基础类
 * Class Wx
 */
class Wx
{

	//protected  $token;
	protected static $config;
	protected        $message;//粉丝发送来的消息

	public function __construct ( $config = [] )
	{
		if ( !self::$config ) {
			//echo 2 .'<hr>';
			self::$config = $config;
		}
		$this->message = $this->getMessage();
	}

	/**
	 * 跟微信进行通讯验证
	 * @return bool
	 */
	public function valid ()
	{
		if ( isset( $_GET[ "signature" ] ) && isset( $_GET[ "timestamp" ] ) && isset( $_GET[ "nonce" ] ) && isset( $_GET[ "echostr" ] ) ) {
			$signature = $_GET[ "signature" ];
			$timestamp = $_GET[ "timestamp" ];
			$nonce     = $_GET[ "nonce" ];

			//			$token  = $this->token;
			$token  = self::$config['token'];
			$tmpArr = [ $token , $timestamp , $nonce ];
			sort( $tmpArr , SORT_STRING );
			$tmpStr = implode( $tmpArr );
			$tmpStr = sha1( $tmpStr );
			//file_put_contents('./a.php','aaaaa');

			if ( $tmpStr == $signature ) {
				echo $_GET[ 'echostr' ];
				exit;
			} else {
				return false;
			}
		}
	}

	/**
	 * 接收粉丝发送来的消息
	 * @return \SimpleXMLElement
	 */
	public function getMessage ()
	{
		//$GLOBALS['HTTP_RAW_POST_DATA'],这个再php低版本中，可以使用接受粉丝发来的消息
		//file_get_contents('php://input')接受粉丝发送来的消息
		//		file_put_contents('./message.php',file_get_contents('php://input'));
		return simplexml_load_string( file_get_contents( 'php://input' ) , 'simpleXmlElement' , LIBXML_NOCDATA );
	}

	/**
	 * 实例化功能类，比如说消息管理类、菜单管理类
	 */
	public function instance ( $name )
	{
		$class = "\wechat\build\\" . ucfirst( $name );

		return new $class;
	}

	/**
	 * curl请求
	 *
	 * @param $url                请求地址
	 * @param string $postData    请求数据
	 *
	 * @return string
	 */
	public function curl ( $url , $postData = '' )
	{
		$ch = curl_init();
		curl_setopt( $ch , CURLOPT_URL , $url );
		curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
		curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , false );
		curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , false );

		if ( $postData ) {
			curl_setopt( $ch , CURLOPT_TIMEOUT , 30 );
			curl_setopt( $ch , CURLOPT_POST , 1 );
			curl_setopt( $ch , CURLOPT_POSTFIELDS , $postData );
		}
		if ( curl_exec( $ch ) === false ) {
			$data = '';
		} else {
			$data = curl_multi_getcontent( $ch );
		}
		curl_close( $ch );

		return $data;
	}

	/**
	 * 获取access_token
	 */
	public function getAccessToken ()
	{
		//http请求方式: GET
//		$accesstoken = $this->curl('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.self::$config['appid'].'&secret='.self::$config['appsecret']);
		//转为php数组
//		$accesstoken = json_decode($accesstoken,true);
//		echo '<pre>';
//		print_r($accesstoken);
		//将数组缓存到文件中wechat/cache/ajas.php
		//文件名
		$filname = md5(self::$config['appid'].self::$config['appsecret']) . '.php';
		//缓存目录
		$cacheDir = __DIR__ . '/cache/';
		is_dir($cacheDir) || mkdir($cacheDir,0777,true);
		//完成文件：
		$fullPath = $cacheDir.$filname;
		//将数据写入文件中，
//		file_put_contents($fullPath,"<?php\r\nreturn ".var_export($accesstoken,true).";");

		//如果缓存有效，读取缓存文件，超过两小时，重新请求
		//文件修改时间+7200              当前时间
		if(is_file($fullPath) && filemtime($fullPath)+7000 > time() )
		{
			//没有超过两小时，缓存有效
			//echo 1;
			$accesstoken = include $fullPath;
		}else{
			//echo 2;
			//缓存失效，重新请求接口
			//http请求方式: GET
			$accesstoken = $this->curl(self::$config['apiUrl'].'/cgi-bin/token?grant_type=client_credential&appid='.self::$config['appid'].'&secret='.self::$config['appsecret']);
			//转为php数组
			$accesstoken = json_decode($accesstoken,true);
			//		echo '<pre>';
			//		print_r($accesstoken);
			file_put_contents($fullPath,"<?php\r\nreturn ".var_export($accesstoken,true).";\r\n?>");
		}
		return $accesstoken['access_token'];
	}

}